package com.chj.service;

import com.chj.dao.repository.OrderItemsRepository;
import com.chj.dao.repository.OrderRepository;
import com.chj.entity.OrderEntity;
import com.chj.entity.OrderItemEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderItemsRepository orderItemsRepository;

    @Transactional
    public long addOne1(OrderEntity entity) {
        entity = this.orderRepository.save(entity);
        return entity.getId();
    }

    public List<OrderEntity> getList1() {
        return this.orderRepository.findAll();
    }

    @Transactional
    public long addOne2(OrderEntity entity) {
        entity = this.orderRepository.save(entity);
        for (OrderItemEntity orderItem : entity.getOrderItems()) {
            orderItem.setOrderNum(entity.getOrderNum());
            orderItemsRepository.save(orderItem);
        }
        return entity.getId();
    }

    public List<OrderEntity> getList2() {
        return this.orderRepository.findAll();
    }

    public OrderEntity getOne2(Long orderNum) {
        OrderEntity order = new OrderEntity();
        order.setOrderNum(orderNum);
        Example<OrderEntity> orderExample = Example.of(order);
        Optional<OrderEntity> one = orderRepository.findOne(orderExample);
        if(one != null && one.isPresent()){
            order = one.get();
            OrderItemEntity orderItem = new OrderItemEntity();
            orderItem.setOrderNum(orderNum);
            Example<OrderItemEntity> orderItemExample = Example.of(orderItem);
            final List<OrderItemEntity> orderItems = orderItemsRepository.findAll(orderItemExample);
            order.setOrderItems(orderItems);
        }
        return order;
    }
}
